<template>
  <section class="auth-wrap">
    <div class="card auth-card">
      <div class="card-header">
        <h2 class="card-title">微信公众号模板消息</h2>
        <p class="subtitle">可选填接收者 OpenID；留空则群发到全部关注者</p>
      </div>
      <div class="row">
        <div class="field" v-if="templatesError">
          <label>模板加载状态</label>
          <div style="color:#b91c1c">{{ templatesError }}</div>
        </div>
        <div class="field">
          <label>接收者 OpenID（可选，留空则发送给全部关注者）</label>
          <input type="text" v-model.trim="touser" placeholder="留空=全部粉丝；填写则仅发送该 OpenID" />
        </div>
        <div class="field">
          <label>选择模板</label>
          <select v-model="template_id">
            <option v-for="t in templates" :key="t.template_id" :value="t.template_id">
              {{ t.title }}（{{ t.template_id }}）
            </option>
            <option v-if="!templatesLoading && !templates.length" value="">暂无模板（请在公众号后台添加）</option>
          </select>
        </div>
        <div class="field">
          <label>模板跳转链接（可选）</label>
          <input type="text" v-model.trim="linkUrl" placeholder="例如 http://www.baidu.com" />
        </div>
        <div class="field">
          <label>模板数据（JSON，可留空使用默认）</label>
          <textarea v-model="dataJson" rows="6" placeholder='留空将使用默认模板数据，或填写合法 JSON'></textarea>
        </div>
      </div>
      <div class="controls">
        <button class="btn btn-primary" @click="send">发送模板消息</button>
      </div>
    </div>
  </section>
  
</template>

<script setup>
import { ref, onMounted } from 'vue'
import http from '@/utils/http'
import { useUiStore } from '@/stores/ui'

const ui = useUiStore()

const touser = ref('')
const template_id = ref('')
const linkUrl = ref('http://www.baidu.com')
const defaultData = {
  nickname: { value: '你的Maya' },
  username: { value: 'china_quanda' },
  websiteName: { value: '百度' },
  websiteUrl: { value: 'http://www.baidu.com' },
  loginTime: { value: '2026年6月23日' },
}
const dataJson = ref(JSON.stringify(defaultData, null, 2))

// 模板列表与加载
const templates = ref([])
const templatesLoading = ref(false)
const templatesError = ref('')

async function loadTemplates() {
  templatesLoading.value = true
  templatesError.value = ''
  try {
    const { data } = await http.get('/api/weixin/templates')
    templates.value = data?.template_list || []
    if (!template_id.value && templates.value.length) {
      template_id.value = templates.value[0].template_id
    }
  } catch (err) {
    templatesError.value = err?.response?.data?.errmsg || err?.message || '加载模板失败'
  } finally {
    templatesLoading.value = false
  }
}
onMounted(loadTemplates)

function parseData() {
  const raw = (dataJson.value || '').trim()
  if (!raw) {
    return defaultData
  }
  try {
    const obj = JSON.parse(raw)
    return obj
  } catch (e) {
    ui.showToast('模板数据 JSON 不合法', 'error')
    throw e
  }
}

async function send() {
  if (!template_id.value) {
    ui.showToast('请选择模板', 'error')
    return
  }
  try {
    const base = {
      template_id: template_id.value,
      url: linkUrl.value || undefined,
      data: parseData(),
    }
    if (!touser.value) {
      const { data } = await http.post('/api/weixin/sendTemplateMessageAll', base)
      ui.showToast(`群发完成：成功 ${data.success}，失败 ${data.failure}`, 'success')
    } else {
      const { data } = await http.post('/api/weixin/sendTemplateMessage', { ...base, touser: touser.value })
      ui.showToast('发送成功，msgid：' + (data.msgid ?? 'ok'), 'success')
    }
  } catch (err) {
    const rid = err?.response?.data?.rid
    const msg = err?.response?.data?.errmsg || err?.message || '发送失败'
    ui.showToast('发送失败：' + msg + (rid ? '（rid: ' + rid + '）' : ''), 'error')
  }
}
</script>

<style scoped>
.auth-wrap { width: 100%; min-height: 85vh; display: flex; align-items: flex-start; justify-content: center; padding: 32px 20px; }
.auth-card { width: 100%; max-width: 920px; padding: 24px; }
.card-header { margin-bottom: 18px; }
.card-title { margin: 0 0 8px; }
.subtitle { color: var(--text-subtle); margin: 0; }
.row { display: grid; grid-template-columns: 1fr; gap: 16px; }
.field label { display: block; font-weight: 600; margin-bottom: 6px; }
input, select { width: 100%; padding: 12px; border-radius: 10px; border: 1px solid var(--color-border); }
input:focus, select:focus { outline: none; border-color: var(--color-primary); box-shadow: var(--ring); }
.controls { margin-top: 16px; display: flex; justify-content: flex-end; }
.card textarea {
  width: 100%;
  resize: vertical;
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  background: #fff;
  outline: none;
}
.card textarea:focus {
  border-color: var(--color-primary, #6366F1);
  box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
}
</style>